<!--最近订单-->
<template>
  <scroll-view scroll-y="true" :style="{ height: scrollH + 'px' }" @scrolltolower="lower">
    <view class="main recent_orders">
      <!-- 最近订单列表 -->
      <view 
        class="box order_lists" 
        v-for="(item, index) in recentOrdersList" 
        :key="index">
        <!-- 时间和支付状态 -->
        <view class="date_type">
          <!-- 时间 -->
          <text class="time">{{ item.orderTime }} {{ item.id }}</text>
          <!-- 支付状态 -->
          <text class="type status" :class="{ status: item.status == 2 }">
            {{ statusWord(item.status) }}
          </text>
        </view>
        <!-- 点菜的内容 -->
        <view class="orderBox" @click="goDetail(item.id)">
          <view class="food_num">
            <scroll-view scroll-x="true" class="pic" style="width: 100%; overflow: hidden; white-space: nowrap">
              <view class="food_num_item" v-for="(num, y) in item.orderDetailList" :key="y">
                <view class="img">
                  <image :src="num.image"></image>
                  <!-- <image src="../../static/img2.jpg"></image> -->
                </view>
                <view class="food">{{ num.name }}</view>
              </view>
            </scroll-view>
          </view>
          <view class="numAndAum">
            <view><text>￥{{ item.amount.toFixed(2) }}</text></view>
            <view><text>共{{ numes(item.orderDetailList).count }}件</text></view>
          </view>
        </view>

        <view class="againBtn">
          <button class="new_btn" type="default" @click="oneOrderFun(item.id)">
            再来一单
          </button>
          <button 
            class="new_btn btn" 
            type="default" 
            @click="goDetail(item.id)"
            v-if="item.status === 1 && getOvertime(item.orderTime) > 0">
            去支付
          </button>
          <!-- 当订单已完成时显示评价按钮 -->
          <button 
            class="new_btn comment-btn" 
            type="default" 
            @click="goComment(item)"
            v-if="item.status === 5">
            去评价
          </button>
        </view>
      </view>
    </view>
    <reach-bottom v-if="loading" :loadingText="loadingText"></reach-bottom>
    <!-- 评价弹窗 -->
    <uni-popup ref="commentPopup" type="bottom">
      <view class="comment-popup">
        <view class="comment-header">
          <text class="comment-title">订单评价</text>
          <text @click="closeCommentPopup" class="close-btn">×</text>
        </view>
        <view class="comment-type">
          <text>评价类型：</text>
          <radio-group @change="onCommentTypeChange">
            <label>
              <radio value="good" :checked="commentType === 'good'" />好评
            </label>
            <label>
              <radio value="bad" :checked="commentType === 'bad'" />差评
            </label>
          </radio-group>
        </view>
        <textarea 
          class="comment-content" 
          placeholder="请输入评价内容" 
          v-model="commentContent"
          maxlength="200"
        ></textarea>
        <button @click="submitComment" class="submit-btn">提交评价</button>
      </view>
    </uni-popup>
  </scroll-view>
</template>
<script>
import ReachBottom from "@/components/reach-bottom/reach-bottom.vue";
import { statusWord } from "@/utils/index";
import { addComment } from '../../api/api.js'
export default {
  // 获取父级传的数据
  props: {
    // 头像
    scrollH: {
      type: Number,
      default: 0,
    },
    //
    loading: {
      type: Boolean,
      default: false,
    },
    loadingText: {
      type: String,
      default: "",
    },
    // 例表数据
    recentOrdersList: {
      type: Array,
      default: () => [],
    },
  },
  components: {
    ReachBottom,
  },
  data() {
    return {
      currentCommentOrder: null,
      commentType: 'good',
      commentContent: ''
    }
  },
  methods: {
    lower() {
      this.$emit("lower");
    },
    //订单详情
    goDetail(id) {
      this.$emit("goDetail", id);
    },
    //  1待付款 2待接单 3 已接单 4 派送中 5 已完成 6 已取消 7 退款 
    numes(list) {
      let count = 0;
      let total = 0;
      list.length > 0 &&
        list.forEach((obj) => {
          count += Number(obj.number);
          total += Number(obj.number) * Number(obj.amount);
        });
      return { count: count, total: total };
    },
    // 再来一单
    oneOrderFun(id) {
      this.$emit("oneOrderFun", id);
    },
    //
    getOvertime(time) {
      this.$emit("getOvertime", time);
    },
    // 支付状态
    statusWord(status, time) {
      return statusWord(status, time);
    },
    // 去评价
    goComment(item) {
      console.group('Go Comment Debug')
      console.log('准备评价的订单:', item)
      
      // 保存当前要评价的订单
      this.currentCommentOrder = item
      
      // 打开评价弹窗前的状态检查
      this._debugComponentState()
      
      // 打开评价弹窗
      this.$refs.commentPopup.open()
      
      console.groupEnd()
    },
    onCommentTypeChange(e) {
      console.log('评论类型变更事件:', e)
      this.commentType = e.detail.value
      console.log('当前评论类型:', this.commentType)
    },
    closeCommentPopup() {
      this.$refs.commentPopup.close()
      // 重置评价数据
      this.resetCommentData()
    },
    submitComment() {
      console.group('Submit Comment Debug')
      
      // 提交前的状态检查
      this._debugComponentState()

      // 校验评价内容
      if (!this.commentContent || !this.commentContent.trim()) {
        uni.showToast({
          title: '请输入评价内容',
          icon: 'none'
        })
        console.warn('评价内容为空')
        console.groupEnd()
        return
      }

      // 校验当前订单
      if (!this.currentCommentOrder || !this.currentCommentOrder.id) {
        uni.showToast({
          title: '无法获取订单信息',
          icon: 'none'
        })
        console.warn('当前订单信息不完整')
        console.groupEnd()
        return
      }

      // 获取用户信息
      const userInfo = uni.getStorageSync('userInfo')
      const username = userInfo ? userInfo.nickName : '匿名用户'

      // 调用评价接口
      const params = {
        parentName: null,  // 明确设置为 null
        rootName: "caiye",
        userName: username,
        content: this.commentContent.trim(),
        sort: null,  // 明确设置为 null
        status: 0,
        type: this.commentType === 'good' ? 1 : 2,
        createTime: null,  // 后端会处理
        updateTime: null,  // 后端会处理
        orderId: this.currentCommentOrder.id  // 添加订单ID
      }

      console.log('评价参数:', JSON.stringify(params))
      console.log('当前订单信息:', this.currentCommentOrder)

      // 调用评价接口
      addComment(params).then(res => {
        console.log('评价接口返回:', res)
        uni.showToast({
          title: '评价成功',
          icon: 'success'
        })
        // 关闭弹窗
        this.$refs.commentPopup.close()
        // 重置评价数据
        this.resetCommentData()
        // 可能需要刷新订单列表
        this.$emit('commentSuccess')
        
        console.groupEnd()
      }).catch(err => {
        console.error('评价接口调用错误:', err)
        // 尝试打印更多错误细节
        console.error('错误对象详情:', JSON.stringify(err, Object.getOwnPropertyNames(err)))
        
        // 根据错误对象显示具体错误信息
        const errorMsg = err.msg || err.message || '评价失败'
        uni.showToast({
          title: errorMsg,
          icon: 'none'
        })
        
        console.groupEnd()
      })
    },
    _debugComponentState() {
      console.group('OrderList Component Debug')
      console.log('当前组件实例:', this)
      console.log('评论内容 (commentContent):', this.commentContent)
      console.log('评论类型 (commentType):', this.commentType)
      console.log('当前评论订单 (currentCommentOrder):', this.currentCommentOrder)
      
      // 检查本地存储
      try {
        const userInfo = uni.getStorageSync('userInfo')
        console.log('本地存储用户信息:', userInfo)
      } catch (error) {
        console.error('获取本地存储用户信息时发生错误:', error)
      }
      
      console.groupEnd()
    },
    resetCommentData() {
      console.log('重置评论数据前的状态:')
      this._debugComponentState()

      // 重置评论相关数据
      this.commentContent = ''
      this.commentType = 'good'
      this.currentCommentOrder = null

      console.log('重置评论数据后的状态:')
      this._debugComponentState()
    }
  }
}
</script>

<style scoped>
.comment-popup {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 20rpx 20rpx 0 0;
}
.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}
.comment-type {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}
.comment-content {
  width: 100%;
  height: 200rpx;
  border: 1rpx solid #eee;
  margin-bottom: 20rpx;
}
.submit-btn {
  width: 100%;
  background-color: #007aff;
  color: white;
}
</style>